//
//  DestinationView.swift
//  iIHS
//
//  Created by iGhibli on 2021/6/29.
//

import Foundation
import Cocoa

protocol DestinationViewDelegate {
    func processImage(_ image: NSImage, _ path: URL?)
}

class DestinationView: NSView {
    
    var delegate: DestinationViewDelegate?
    var isReceivingDrag = false {
        didSet {
            needsDisplay = true
        }
    }
    
    override func awakeFromNib() {
        registerForDraggedTypes([NSPasteboard.PasteboardType.fileURL])
    }
    
    override func draw(_ dirtyRect: NSRect) {
        // 绘制虚线边框
        let path = NSBezierPath(rect: dirtyRect)
        NSColor.clear.setFill()
        path.fill()
        NSColor.lightGray.setStroke()
        path.lineWidth = 1
        path.stroke()
        // 绘制十字线
        path.move(to: NSPoint(x: dirtyRect.width/4, y: dirtyRect.height/2))
        path.line(to: NSPoint(x: dirtyRect.width/4*3, y: dirtyRect.height/2))
        path.move(to: NSPoint(x: dirtyRect.width/2, y: dirtyRect.height/4))
        path.line(to: NSPoint(x: dirtyRect.width/2, y: dirtyRect.height/4*3))
        path.stroke()
    }
    
    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
        return .copy
    }
    
    override func draggingExited(_ sender: NSDraggingInfo?) {
        isReceivingDrag = false
    }
    
    override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
        return true
    }
    
    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        isReceivingDrag = false
        let pasteBoard = sender.draggingPasteboard
        guard let image = NSImage(pasteboard: pasteBoard), let fileURL = pasteBoard.pasteboardItems?[0].string(forType: .fileURL) else {
            return false
        }
        let path = URL.init(string: fileURL)
        delegate?.processImage(image, path)
        return true
    }

}
